package com.liu.demo1.testDemo;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author liusiyu
 * @ClassName IOTest
 * @date 2021年12月18日 21:13
 */
public class BIO {

    @Test
    public void server() throws IOException{

        ServerSocket ss = new ServerSocket();
        ss.bind(new InetSocketAddress(8081));

        while (true){
            System.out.println("等待连接...");
            Socket newS = ss.accept();  // 阻塞
            System.out.println("新连接："+newS.getRemoteSocketAddress());

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream in = newS.getInputStream();
                        while (true){
                            byte[] buffer = new byte[16];
                            System.out.println(newS.getRemoteSocketAddress() + "开始读取...");
                            int len = in.read(buffer); // 阻塞
                            System.out.println(newS.getRemoteSocketAddress() + "读取到数据：" + new String(buffer,"utf-8"));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    @Test
    public void client() throws IOException{
        Socket socket = new Socket("localhost",8081);
        OutputStream outputStream = socket.getOutputStream();
        System.out.println("debug");
    }

}
